<template>
  <div>
    <t-form ref="form" class="form-container" :data="formData" :rules="FORM_RULES" label-width="0" @submit="onSubmit">
      <template>
        <t-form-item name="phone">
          <t-input v-model="formData.name" :maxlength="30" size="large" placeholder="姓名" clearable>
            <template #prefix-icon>
              <user-icon />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item name="orgName">
          <t-input v-model="formData.orgName" :maxlength="30" size="large" placeholder="公司全称" clearable>
            <template #prefix-icon>
              <control-platform-icon />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item name="dapartment">
          <t-input v-model="formData.dapartment" :maxlength="30" size="large" placeholder="所在部门" clearable>
            <template #prefix-icon>
              <app-icon />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item name="position">
          <t-input v-model="formData.position" :maxlength="30" size="large" placeholder="职务名称" clearable>
            <template #prefix-icon>
              <usergroup-icon />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item name="email">
          <t-input v-model="formData.email" :maxlength="50" size="large" placeholder="邮箱" @blur="testEmail" clearable>
            <template #prefix-icon>
              <mail-icon />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item name="phone">
          <t-input
            v-model="formData.phone"
            :maxlength="11"
            size="large"
            placeholder="手机号"
            @blur="testPhone"
            clearable
          >
            <template #prefix-icon>
              <mobile-icon />
            </template>
          </t-input>
        </t-form-item>
        <t-form-item name="code">
          <t-input
            v-model="formData.code"
            size="large"
            placeholder="请输入验证码"
            key="code"
            class="verify-inp"
            clearable
          />
          <t-button variant="outline" :disabled="countDown > 0" @click="sendCode" class="verify-btn">
            {{ countDown == 0 ? ' 发送验证码 ' : `${countDown}秒后可重发` }}
          </t-button>
        </t-form-item>
      </template>

      <div class="check-container remember-pwd">
        <t-checkbox v-model="checked">
          <span>
            我已阅读并同意
            <a href="https://www.pis360.com/privacy-policy" target="_blank" style="margin-right: 0">隐私政策</a>
            和
            <a href="https://www.pis360.com/agreement" target="_blank">用户协议</a>
          </span>
        </t-checkbox>
      </div>
      <t-dialog
        theme="success"
        header="您的申请已成功提交！"
        :top="'20%'"
        width="17%"
        :footer="false"
        :closeOnOverlayClick="false"
        :visible.sync="visible"
        @confirm="onConfirm"
        :onClose="close"
      >
        <div slot="body">
          <p>我们将尽快安排专属顾问与您联系，请注意保持联系方式畅通。感谢您的支持！</p>
        </div>
      </t-dialog>
      <t-form-item>
        <t-button block size="large" type="submit" :disabled="showDialog"> 提交申请 </t-button>
      </t-form-item>
    </t-form>
    <swiper />
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import Swiper from './Swiper.vue';
import { UserIcon, ControlPlatformIcon, AppIcon, UsergroupIcon, MailIcon, MobileIcon } from 'tdesign-icons-vue';
import { verificationCode } from '@/service/login/index';

const INITIAL_DATA = {
  code: '',
  dapartment: '',
  email: '',
  name: '',
  orgName: '',
  phone: '',
  position: '',
};

const FORM_RULES = {
  code: [{ required: true, message: '验证码必填', type: 'error' }],
  dapartment: [{ required: true, message: '所在部门必填', type: 'error' }],
  email: [{ required: true, message: '邮箱必填', type: 'error' }],
  name: [{ required: true, message: '姓名必填', type: 'error' }],
  orgName: [{ required: true, message: '公司全称必填', type: 'error' }],
  phone: [{ required: true, message: '手机号必填', type: 'error' }],
  position: [{ required: true, message: '职务必填', type: 'error' }],
};

/** 高级详情 */
export default Vue.extend({
  name: 'Register',
  components: {
    UserIcon,
    ControlPlatformIcon,
    AppIcon,
    UsergroupIcon,
    MailIcon,
    MobileIcon,
    Swiper,
  },
  data() {
    return {
      showDialog: false,
      visible: false,
      checked: false,
      FORM_RULES,
      type: 'phone',
      emailOptions: [],
      formData: { ...INITIAL_DATA },
      showPsw: false,
      countDown: 0,
      intervalTimer: null,
    };
  },
  beforeDestroy() {
    clearInterval(this.intervalTimer);
  },
  methods: {
    async onSubmit({ validateResult }: { validateResult: boolean }) {
      if (validateResult === true) {
        if (!this.checked) {
          this.$message.error('请同意英斯盾隐私政策和用户协议');
          return;
        }
        if (this.testEmail() && this.testPhone()) {
          this.$message.error('邮箱或手机号错误');
          return;
        }
        this.$store.dispatch('user/register', this.formData).then((res) => {
          if (res.data?.code === 200) {
            // this.$message.success('注册成功');
            this.showDialog = true;
            this.visible = true;
            // this.$emit('registerSuccess');
          } else {
            // this.$message.error(`${res.data.message}`);
          }
        });
      }
    },
    // 发送验证码
    async sendCode() {
      const phone = { phone: this.formData.phone };
      if (this.testEmail()) {
        this.$message.warning('请输入正确的企业邮箱');
        return;
      }
      if (this.testPhone()) {
        this.$message.warning('请输入正确的手机号');
        return;
      }

      await verificationCode(phone);

      this.countDown = 60;
      this.intervalTimer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1;
        } else {
          clearInterval(this.intervalTimer);
          this.countDown = 0;
        }
      }, 1000);
    },
    testPhone() {
      // 判断手机号是否正确
      const phoneNumber = /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/;
      if (!phoneNumber.test(this.formData.phone)) {
        // this.phoneTest = false;
        return true;
      }
      return false;
    },
    testEmail() {
      // 判断邮箱是否正确
      const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!email.test(this.formData.email)) {
        // this.emailTest = false;
        return true;
      }
      if (this.isBusinessEmail(this.formData.email)) {
        return true;
      }
      return false;
    },
    onConfirm(context) {
      const { e } = context;
      // todo something else here
      // this.sendingRequest();
      this.visible = false;
      e.stopPropagation();
    },
    close() {
      this.visible = false;
    },
    // 是否是企业邮箱
    isBusinessEmail(email) {
      const usualEmail = ['163.com', '126.com', 'qq.com', 'gmail.com', 'yeah.com', 'sina.com', 'hotmail.com'];
      const newEmail = email.slice(email.length - 11, email.length);
      return usualEmail.some((item) => {
        if (newEmail.indexOf(item) >= 0) {
          return item;
        }
        return false;
      });
    },
  },
});
</script>
<style lang="less" scoped>
@media screen and (min-width: 768px) {
  /deep/.web-login {
    margin: 100px 50px 0 50px !important;
  }
  .form-container {
    width: 375px !important;
    margin-top: 20px;

    .verify-inp {
      margin-right: 20px;
    }
    /deep/.form-container .t-form {
      margin-right: 50px !important;
    }
    .verify-btn {
      width: 9vw;
    }
  }
}
@media screen and (max-width: 768px) {
  /deep/.login-swiper {
    display: none;
  }
}
</style>
